package com.youlai.boot.core.security.util;

import com.youlai.boot.factory.model.entity.FactoryMember;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * 外部用户安全工具类
 *
 * @author YourName
 * @since 2025/3/7
 */
public class ExternalSecurityUtils {

    /**
     * 获取当前登录的外部用户信息
     *
     * @return Optional<FactoryMember>
     */
    public static Optional<FactoryMember> getFactoryMember() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof FactoryMember) {
                return Optional.of((FactoryMember) principal);
            }
        }
        return Optional.empty();
    }

    /**
     * 获取外部用户ID
     *
     * @return Long
     */
    public static Long getFactoryMemberId() {
        return getFactoryMember().map(FactoryMember::getId).orElse(null);
    }

    /**
     * 获取外部用户名称
     *
     * @return String
     */
    public static String getFactoryMemberName() {
        return getFactoryMember().map(FactoryMember::getName).orElse(null);
    }
}
